<?php
/**
 * gpa_new Description
 * @package
 * @name model_gallery
 * @filesource model_gallery.php
 * @author Meta Sanjaya
 */

class model_gallery extends Model
{
    /**
     * @access public
     * @method __construct
     * @param void
     * @return void
     */
    public function  __construct()
    {
        parent::__construct();
    }

    public function getAllImages($scope='gallery') {
        return $this->db->query("SELECT * FROM #_gallery_images WHERE published='1'")->rows;
    }

    public function getImages($scope='gallery', $start=0, $limit=30) {
        $imgs = array();
        $images = $this->db->query("SELECT a.image_id FROM #_gallery_images a JOIN #_gallery_images_albums b ON a.image_id = b.image_id JOIN #_users_albums c ON b.album_id = c.album_id WHERE a.published='1' AND a.scope='$scope' AND c.private = '0' ORDER BY a.time_stamp DESC LIMIT $start, $limit")->rows;

        for($i=0, $j=count($images); $i<$j; $i++) {
            $options['thumb_size'] = getInstance('config')->get($scope . '_thumb_size');
            $imgs[] = $this->getImageById($images[$i]['image_id'], $options);
        }

        return $imgs;
    }

    public function getImageById($iid, $options=array())
    {
        $image = array();
        $published = !isset($options['published_search'])?" AND a.published='1'":"";
        $rows = $this->db->query("SELECT a.*, b.description FROM #_gallery_images a LEFT JOIN #_gallery_images_description b ON b.image_id=a.image_id WHERE a.image_id='$iid'" . $published)->rows;
        //var_dump($this->db->getQuery());
        if(isset($rows[0])) {
            $image = $rows[0];
            $image['user_comments'] = $this->getImageComments($iid);
            $image['recommended_by'] = $this->getImageRecomendedBy($iid);
            $image['info'] = $this->getImageInfo($iid);
            $image['categories'] = $this->getImageCategories($iid);
            $image['tags'] = $this->getImageTags($iid);
            $image['href'] = getImgUrl() . "fullscreens/" . $image['file'];
            $image['url'] = getAppUrl($image['scope'],'view_image') . "/" . $iid;
            $image['thumb'] = $this->getImageThumb($iid, $options['thumb_size']);
        }

        return $image;
    }

    public function setImage($iid, $datas=array()) {
        $this->db->query("UPDATE #_gallery_images SET title = '".$this->db->escape(htmlspecialchars($datas['title']))."', published = '".$datas['published']."' WHERE image_id = '$iid'");
    }

    public function viewImage($iid) {
        $view = $this->db->query("SELECT viewed FROM #_gallery_images WHERE image_id = '$iid'")->rows[0]['viewed'];
        $this->db->query("UPDATE #_gallery_images SET viewed = '".(++$view)."' WHERE image_id = '$iid'");
    }

    public function getImagesById($ids=array(), $options=array()) {
        $images = array();

        foreach($ids as $id) {
            $images[] = $this->getImageById($id, $options);
        }
        
        return $images;
    }

    public function setImageDescription($iid, $desc='') {
        $this->db->query("DELETE FROM #_gallery_images_description WHERE image_id = '$iid'");
        $this->db->query("INSERT INTO #_gallery_images_description SET image_id = '$iid', description = '".$this->db->escape($desc)."'");
    }

    public function getImageThumb($iid, $thumb_size) {
        loadLibrary('Image', false);

        $image = $this->db->query("SELECT file FROM #_gallery_images WHERE image_id = '$iid'")->rows[0]['file'];

        $imagepath = getImgPath() . "fullscreens/" . $image;
        $thumbpath = getImgPath() . "thumbnails/" . $thumb_size . "/";

        if(!is_dir($thumbpath)) {
            mkdir($thumbpath);
            chmod($thumbpath, 0777);
            file_put_contents($thumbpath . "index.html", "");
        }

        $info = getimagesize($imagepath);

        if($info[1] > $info[0]) {
            $nwidth = 0;
            $nheight = $thumb_size;
        } else {
            $nwidth = $thumb_size;
            $nheight = 0;
        }

        return @(getImgUrl() . create_thumbnail($imagepath, $nwidth, $nheight, $thumbpath, getImgPath()));
    }

    public function getImageInfo($iid) {
        $info = array();

        $json = @$this->db->query("SELECT infos FROM #_gallery_images_infos WHERE image_id = '$iid'")->rows[0]['infos'];
        
        if($json) {
            if(empty($json)) {
                $json = "{}";
            }
            
            $info = json_decode($json, true);
        }

        return $info;
    }

    public function setImageInfo($iid, $infos=array()) {
        $this->db->query("DELETE FROM #_gallery_images_infos WHERE image_id = '$iid'");
        $this->db->query("INSERT INTO #_gallery_images_infos SET image_id = '$iid', infos = '".$this->db->escape(json_encode($infos))."'");
    }

    public function getImageTags($iid) {
        $tags = array();

        $json = @$this->db->query("SELECT tags FROM #_gallery_images_tags WHERE image_id = '$iid'")->rows[0]['tags'];

        if($json) {
            if(empty($json)) {
                $json = "{}";
            }

            $tags = json_decode($json);
        }

        return $tags;
    }

    public function setImageTags($iid, $tags=array()) {
        $this->db->query("DELETE FROM #_gallery_images_tags WHERE image_id = '$iid'");
        $this->db->query("INSERT INTO #_gallery_images_tags SET image_id = '$iid', tags = '".$this->db->escape(json_encode($tags))."'");
    }

    public function getImageCategories($iid) {
        $cats = array();

        $json = @$this->db->query("SELECT categories FROM #_gallery_images_categories WHERE image_id = '$iid'")->rows[0]['categories'];

        if($json) {
            if(empty($json)) {
                $json = "{}";
            }

            $cids = json_decode($json);

            $model_category = $this->getModel('category');
            foreach($cids as $cid) {
                $cats[] = $model_category->getCategoryById($cid);
            }
        }

        return $cats;
    }

    public function setImageCategories($iid, $cats=array()) {
        $this->db->query("DELETE FROM #_gallery_images_categories WHERE image_id = '$iid'");
        $this->db->query("INSERT INTO #_gallery_images_categories SET image_id = '$iid', categories = '".$this->db->escape(json_encode($cats))."'");
    }

    public function getImageRecomendedBy($iid) {
        $users = array();

        $rows = $this->db->query("SELECT user_id FROM #_gallery_images_recomended_by_users WHERE image_id = '$iid'")->rows;
        foreach($rows as $user) {
            $users[] = $this->db->query("SELECT user_id, username FROM #_users WHERE user_id = '".$user['user_id']."'")->rows[0];
        }

        return $users;
    }

    public function setImageRecomendedBy($iid, $uid) {
        $this->db->query("INSERT INTO #_gallery_images_recomended_by_users SET image_id = '$iid', user_id = '$uid'");
    }

    public function getImageComments($iid, $start=0, $limit=30)
    {
        $return = array();
        $model_comment = $this->getModel('comment');
        $comments = $this->db->query("SELECT * FROM #_comment_image_comments a JOIN #_comment_users_comments b ON b.comment_id = a.comment_id WHERE a.image_id='$iid' ORDER BY b.time_stamp LIMIT $start, $limit")->rows;
        $uid = User::getUserId();

        foreach($comments as $comment) {
            $comment['is_user_comment'] = $model_comment->isUserComment($comment['comment_id']);
            $comment['is_recommended_comment'] = $model_comment->isCommentRecommendedBy($comment['comment_id']);

            $return[] = $comment;
        }

        return $return;
    }

    public function setImageComment($iid, $uid, $comment)
    {
        $comment = $this->db->escape(htmlspecialchars($comment));

        $this->db->query("INSERT INTO #_comment_users_comments SET user_id='$uid', comment='$comment'");
        $cid = $this->db->getInsertId();

        $this->db->query("INSERT INTO #_comment_image_comments SET image_id='$iid', comment_id='$cid'");
        return true;
    }

    public function addImage($datas) {
        if(isset($datas['tmp_name'])) {
            $file_name = str_replace('.', '', microtime(true)) . md5($datas['name']) . '.jpg';
            if(@move_uploaded_file($datas['tmp_name'], getImgPath() . 'fullscreens/' . $file_name )) {
                $this->db->query("INSERT INTO #_gallery_images SET scope = '".$datas['scope']."', title = '".$this->db->escape(htmlspecialchars($datas['title']))."', file = '".$this->db->escape($file_name)."', published = '".$datas['published']."'");
                //echo $this->db->getQuery();
                //exit;
                $iid = $this->db->getInsertId();
                
                $this->setImageDescription($iid, $datas['desc']);
                $this->setImageCategories($iid, $datas['cats']);
                $this->setImageTags($iid, $datas['tags']);
                $this->setImageInfo($iid, $datas['info']);

                $model_album = $this->getModel('album');

                if(!isset($datas['album_id'])) {
                    $aid = $model_album->getPublicAlbum(User::getUserId());
                }
                
                $model_album->addImageToAlbum($iid, $datas['album_id']);

                if($datas['scope'] == "screening") {
                    $this->db->query("INSERT INTO #_screening_images_point SET image_id = '$iid'");
                }

                return $iid;
            }

            return false;
        }

        return false;
    }
}
?>